package com.qkun.library.widget;

import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;

import com.qkun.library.utils.Utils;

/**
 * 在activity上添加progressBar
 * <p>
 * 也许可以考虑使用:
 * <p>ContentLoadingProgressBar</p>需要设置style才会绘制出来
 * <code>new ContentLoadingProgressBar(new ContextThemeWrapper(activity, R.style.Widget_AppCompat_ProgressBar));</code>
 */
// TODO: 11/8 0008 可以考虑加上一层蒙层
public final class GlobalProgressBarWidget {

    @NonNull
    private final ProgressBar mProgressBar;
    @NonNull
    private final Activity mActivity;

    private boolean mIsShowing;

    private GlobalProgressBarWidget(@NonNull Activity activity) {
        mActivity = activity;
        mProgressBar = new ProgressBar(activity);
        FrameLayout.LayoutParams layoutParams =
                new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        mProgressBar.setLayoutParams(layoutParams);
    }

    public static GlobalProgressBarWidget newInstance(@NonNull Activity activity) {
        return new GlobalProgressBarWidget(activity);
    }

    public void toggle(boolean show) {
        if (mIsShowing != show) {
            mIsShowing = show;
            if (show) {
                View rootView = mActivity.getWindow().getDecorView();
                if (rootView instanceof ViewGroup) {
                    ViewGroup rootLayout = (ViewGroup) rootView;
                    ViewParent parent = mProgressBar.getParent();
                    if (rootLayout == parent) return;
                    Utils.requestParentRemoveView(mProgressBar);
                    rootLayout.addView(mProgressBar);
                    mActivity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                }
            } else {
                Utils.requestParentRemoveView(mProgressBar);
                mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            }
        }
    }

    public boolean isShowing() {
        return mIsShowing;
    }
}
